package com.pay.cloud.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.pay.cloud.KeyInfo;
import com.pay.cloud.KeyInfoListener;
import com.pay.cloud.PwdCheckerDefault;
import com.pay.cloud.PwdValidator;
import com.pay.cloud.R;


public class PwdValidateFragment extends AbstractFragment implements PwdInputFragment.OnPwdListener, KeyInfoListener {
    private PwdInputFragment pwdInput = new PwdInputFragment();
    private PwdValidator validator;
    private OnPwdListener listener;
    public PwdValidateFragment() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_password, container, false);
        setValidator(new PwdCheckerDefault());
        pwdInput.setOnPwdListener(this);

        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.password_main_container, pwdInput);
        fragmentTransaction.commit();

        return view;
    }

    public void setValidator(PwdValidator validator) {
        this.validator = validator;
    }

    public void setOnPwdValidateListener(OnPwdListener listener) {
        this.listener = listener;
    }

    @Override
    public boolean onKeyDown(KeyInfo keyInfo) {
        return pwdInput.onKeyDown(keyInfo);
    }

    @Override
    public void finish(String pwd) {
        boolean isValid = validator.isValid(pwd);
        if (!isValid) {
            handle(() -> Toast.makeText(pwdInput.getContext(), pwdInput.getContext().getString(R.string.pwd_invalid), Toast.LENGTH_SHORT).show());
            handleDelay(() -> pwdInput.clear(), 300);
        } else {
            if (null != listener) {
                listener.onPwdValid();
            }
        }
    }

    public interface OnPwdListener {
        void onPwdValid();
    }
}
